package org.dream.persistence;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dream.util.ReflectUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * 
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class BaseDAOImpl implements BaseDAO {
	protected Log logger = LogFactory.getLog(this.getClass());
	protected SessionFactory sessionFactory;
	protected Class entityClass;

	/**
	 * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型Class. eg. public class UserDao extends
	 * SimpleHibernateDao<User, Long>
	 */
	public BaseDAOImpl() {
		this.entityClass = ReflectUtil.getSuperClassGenricType(getClass());
	}

	public void save(Object entity) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.save(entity);
		session.getTransaction().commit();
	}

	public void saveList(List list) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		try {
			for (Object daydeal : list) {
				session.save(daydeal);
			}
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}

	}

	public void clearDB(Class class1) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.createQuery("delete from " + class1.getSimpleName()).executeUpdate();
		session.getTransaction().commit();
	}

	public boolean isEmpty(String table) {
		try {
			String sql = "select top 1 id from " + table;
			Statement stmt = DBUtil.getStatement();
			org.dream.util.LogFactory.getLog().logSql(sql);
			ResultSet rs = stmt.executeQuery(sql);

			if (rs.next()) {
				return false;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	public List findAll(Class class1) {
		return HibernateSessionFactory.getSession().createQuery("from " + class1.getSimpleName()).list();
	}

	public void update(Object daydeal) {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.update(daydeal);
		session.getTransaction().commit();
	}

}
